package com.personal.dao.copyonwrite;

import java.io.Serializable;
import java.util.AbstractMap;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * CopyOnWriteHashMap
 * @author cuibo
 *
 * @param <K>
 * @param <V>
 */
public class CopyOnWriteHashMap<K, V> extends AbstractMap<K, V> implements Map<K, V>, Cloneable, Serializable
{

    /**
     * 
     */
    private static final long serialVersionUID = 946739924579621429L;

    private transient volatile Map<K, V> backingMap = null;

    public CopyOnWriteHashMap()
    {
        this.backingMap = new HashMap<K, V>();
    }

    public CopyOnWriteHashMap(int paramInt, float paramFloat)
    {
        this.backingMap = new HashMap<K, V>(paramInt, paramFloat);
    }

    public CopyOnWriteHashMap(int paramInt)
    {
        this(paramInt, 0.75F);
    }

    public CopyOnWriteHashMap(Map<? extends K, ? extends V> paramMap)
    {
        this.backingMap = new HashMap<K, V>(paramMap);
    }

    @Override
    public V put(K key, V value)
    {
        synchronized (this)
        {
            Map<K, V> newMap = new HashMap<K, V>(backingMap);
            newMap.put(key, value);
            backingMap = newMap;
            return value;
        }
    }

    @Override
    public V get(Object key)
    {
        return backingMap.get(key);
    }

    @Override
    public Set<Entry<K, V>> entrySet()
    {
        throw new UnsupportedOperationException("暂不支持此操作！");
    }
}
